"use client";
import ButtonOwn from "@/components/ButtonOwn";
import { Link, useRouter } from "@/i18n";
import { useUserInfoStore } from "@/stores/useUserInfoStore";
import { Toast } from "antd-mobile";
import clsx from "clsx";
import { useTranslations } from "next-intl";
import { useSearchParams } from "next/navigation";
import { FC, FormEvent, PropsWithChildren, useState } from "react";
import { useFormStatus } from "react-dom";
import { loginAction, registerAction } from "./action";
import "./style.scss";

/**
 * @description 登录注册From表单
 * @param {string} type 使用类型 login 或 register
 * @param {string} msgError 错误提示 login 或 register
 * @param {(params: any) => void} callbackFun 回调方法
 */
export interface FromComProps {
    type?: string;
    msgError?: string;
    callbackFun?: (params: any) => void;
}
const initialState = {
    message: "",
};
const Submit = (props: { text: string }) => {
    const { text } = props;
    const { pending, data } = useFormStatus();
    return (
        <ButtonOwn disabled={pending} type={"submit"} active={true}>
            {text}
        </ButtonOwn>
    );
};

const FromCom: FC<PropsWithChildren<FromComProps>> = ({ type = "login", msgError = "" }) => {
    const t = useTranslations("LoginPage");
    let [pwdVisible, setPwdVisible] = useState(false);
    const searchParams = useSearchParams();
    const router = useRouter();
    const { setUserInfo } = useUserInfoStore();
    const [loginFormStatus, setLoginFormStatus] = useState<{ success?: boolean; message?: string }>(
        {}
    );

    const formAction = async (formData: FormData) => {
        if (!formData.get("userPhone")) {
            setLoginFormStatus({ success: false, message: "Please input phoneNumber" });
            return;
        }
        if (!formData.get("pwd")) {
            setLoginFormStatus({ success: false, message: "Please input password" });
            return;
        }
        Toast.show({ icon: "loading", duration: 3000, maskClickable: false });
        if (type === "login") {
            const result = await loginAction(formData);
            setUserInfo(result.user);
            setLoginFormStatus(result);
            if (result.success) {
                router.replace(searchParams.get("redirect") || "/");
            }
        } else {
            formData.set("referrer_code", sessionStorage.getItem("shareId") ?? "");
            const result = await registerAction(formData);
            if (result.success) {
                // const loginResult = await loginAction(formData);
                // setUserInfo(loginResult.user);
                // setToken(loginResult.token!);
                // setLoginFormStatus(result);
                // if (result.success) {
                //     router.replace(searchParams.get("redirect") || "/");
                // }
                router.replace("/login");
            } else {
                setLoginFormStatus({ success: false, message: result.message });
            }
        }
        Toast.clear();
    };
    const onsubmit = async (e: FormEvent<HTMLFormElement>) => {
        e.preventDefault();
        const formData = new FormData(e.target as HTMLFormElement);
        await formAction(formData);
    };

    const spanClassName = clsx("iconfont", {
        "icon-kejian": pwdVisible,
        "icon-bukejian": !pwdVisible,
    });

    return (
        <div className="FromCom">
            <form onSubmit={onsubmit}>
                <div className="phoneInput">
                    <span className="after">{t("areaCode")}</span>
                    <input name="userPhone" type="tel" placeholder={t("Celular")} maxLength={11} />
                </div>
                <div className="passwordInput">
                    <input
                        name="pwd"
                        type={pwdVisible ? "text" : "password"}
                        placeholder={t("Senha")}
                        maxLength={12}
                    />
                    <span
                        className={spanClassName}
                        onClick={() => setPwdVisible(!pwdVisible)}
                    ></span>
                </div>
                <div className="btnContent">
                    <div className="tips"> {loginFormStatus.message} </div>
                    <Submit text={type == "login" ? "Login" : t("register")} />
                </div>
            </form>
            <div className="link">
                {type == "login" ? (
                    <>
                        <Link href="/resetPhone">{t("forgetPwd")}</Link>
                        <Link href="/register">{t("registerGo")}</Link>
                    </>
                ) : (
                    <Link href="/login" className="active" replace>
                        {t("loginGo")}
                    </Link>
                )}
            </div>
        </div>
    );
};

export default FromCom;
